import axios from 'axios';
import { GET_TOKEN } from './token.js';
import { showFailToast } from 'vant';
import { useUserStore } from '@/stores/modules/userStore';
const request = axios.create({
    baseURL: import.meta.env.VITE_APP_BASE_API,
    // 测试服测试 api/
    // 正式服打包 /yxt2/api/
    timeout: 8000
});

request.interceptors.request.use(
    config => {
        const token = GET_TOKEN();

        if (token) {
            config.headers.Authorization = `Bearer ${token}`;
        }

        return config;
    },
    error => {
        return Promise.reject(error);
    }
);

request.interceptors.response.use(
    response => {
        const userStore = useUserStore();
        if (response.status == 200) {
            /**
             * 这是token失效的情况
             */
            if (response.data.statusText == '该token已过期') {
                debugger;
                userStore.logout();
                response.data.statusText = '登录已过期,请重新登录';
                return response.data;
            }
            return response.data;
        } else {
            return Promise.reject(response.data);
        }
    },
    error => {
        if (
            error.code === 'ECONNABORTED' &&
            error.message.indexOf('timeout') !== -1
        ) {
            // 超时错误处理
            showFailToast('请求超时');
        }
        return Promise.reject(error);
    }
);

export default request;
